'''
感谢okfu_DL提供了验证码识别训练模型 https://blog.csdn.net/okfu_DL
新增功能为：
1、分割3字符识别
2、浏览器防止网页debug
3、防止验证码频繁出错
4、图鉴放大图片
5、识别是否有中文
6、颜色通道置换
7、中文去除黑字
'''

from selenium import webdriver
import time
import base64
from captcha_predict import predict
from captcha_predict3 import predict3
import pandas as pd
from selenium.webdriver.chrome.options import Options
import csv
from datetime import datetime
import json
import requests
import urllib.parse
from selenium.webdriver.common.action_chains import ActionChains
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import matplotlib.pyplot as plt
import numpy as np
import configparser
from ctypes import *
import random
import binascii
import os
from subprocess import Popen
from io import BytesIO
from sys import version_info
import fateadm_api as ff
import cv2


#调用图鉴识别中文准确率50%
def base64_api(uname, pwd,  img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="png")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    #data = {"username": uname, "password": pwd, "image": b64}
    data = {"username": uname, "password": pwd, "typeid":7,"image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""

def tj(tname):  #图鉴识别
    img_path = tname
    img = Image.open(img_path)
    result = base64_api(uname='*****', pwd='*****', img=img)
    print('图鉴:',result)    
    return result
#英文验证码用TensorFlow,中文用云打码


def readpz():   #读取配置
    conf=configparser.ConfigParser()
    conf.read('peizhi.ini',encoding= 'utf-8-sig')
    
    #调用get方法，然后获取配置的数据
    pz1=conf.get("fpyzm","start")
    pz2=conf.get("fpyzm","end")
    #stmp=conf.get("email_qq","stmp")
    pz3=conf.get("fpyzm","port")
    pz4=conf.get("fpyzm",'fname')
    pz5=conf.get("fpyzm",'yzlog')
    pz6=conf.get("fpyzm",'fplx')
    pz7=conf.get("fpyzm",'hand')  #是否手工
    pz8=conf.get("fpyzm",'path')  #webdriver路径
    print ('开始',pz1,'结束',pz2,'无浏览器',pz3,'文件',pz4,'日志',pz5)
    return pz1,pz2,pz3,pz4,pz5,pz6,pz7,pz8

def qg1(fname1):  #验证码切割成2部分
    #tp=Image.new('RGB',(90,35),'white')
    #tp1=Image.new('RGB',(90,35),'white')
    img = Image.open(fname1)
    #print(img.size)
    cropped = img.crop((1, 0, 44, 35))  # (left, upper, right, lower)
    #tp.paste(cropped,(20,0))
    tp = cropped.resize((90, 35),Image.ANTIALIAS)  #将3字符放大到35*90
    ft=time.strftime("%Y%m%d-%H%M%S")
    fn1='.\\qg\\qg1_'+ft+'.png'
    fn2='.\\qg\\qg2_'+ft+'.png'              #定义文件名
    tp.save(fn1)
    
    cropped = img.crop((40, 0, 83, 35))  # (left, upper, right, lower)
    #tp1.paste(cropped,(20,0))
    tp1 = cropped.resize((90, 35),Image.ANTIALIAS)
    tp1.save(fn2)
    return fn1,fn2

def changey(fname):   #黄色文字颜色处理
    src=cv2.imread(fname,1)
    img_info=src.shape
    image_height=img_info[0]
    image_weight=img_info[1]
    dst=np.zeros((image_height,image_weight,3),np.uint8)
    for i in range(image_height):
        for j in range(image_weight):
            (b,g,r)=src[i][j]
            if b<80 and g>190 and r>190 :
                dst[i][j]=(255-r,255-g,255-b)    
            else :
                dst[i][j]=src[i][j]
    #cv2.imshow('src',src)
    #cv2.imshow('dst',dst)
    cv2.imwrite(fname,dst) 
    cv2.waitKey(0)

def changeb(fname):   #处理蓝色字符
    # cv2 中默认读入图像是(B,G,R)
    #img = cv2.imread(fname)
    img = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1) # 中文文件名
    #print(img)
    #cv2.imshow("raw", img)
    # 黄色转红色
    #img = cv2.bitwise_not(img)  # 黄色R、G值较大，B值较小，先取反，则R、G值较小, B值独大，接近蓝色分布
    #img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)  # 与蓝色转红色相同
    
    # 蓝色转红色
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)  # 蓝色R、G值较小，B值独大，B、G交换，接近红色分布
    
    # 黑色转红色
    #img[:, :, 2] = 255 - img[:, :, 2]  # 黑色三个通道都比较小， 用255-R通道，则R通道独大，其余通道小，接近红色的分布
            
    #cv2.imwrite('.\\img1\\'+str(m),img)
    cv2.imencode('.png', img)[1].tofile(fname)  #中文文件名
    cv2.waitKey(0)

def bgcl(fname):  #中文清理背景色
    #src=cv2.imread(fname,1)
    src = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1)
    img_info=src.shape
    image_height=img_info[0]
    image_weight=img_info[1]
    dst=np.zeros((image_height,image_weight,3),np.uint8)
    (b2,g2,r2)=(255,255,255)
    color=[]
    for i in range(image_height):
        for j in range(image_weight):
            (b,g,r)=src[i][j]
            #dst[i][j]=(255-b,255-g,255-r)
            #print (b,g,r)
            count=0
            while count<10 and j<80:
                (b1,g1,r1)=src[i][j+count+1]
                #print(b,g,r,b1,g1,r1)
                if (b,g,r)==(b1,g1,r1):
                    count=count+1
                    #print(b,g,r,b1,g1,r1)
                    #print (count)
                else :
                    break
    
                if (b,g,r) in color:
                    break
                
            if count==9:
                (b2,g2,r2)=(b,g,r)
                color.append((b2,g2,r2))
    dst2=np.zeros((image_height,image_weight,3),np.uint8)
    for k in range(image_height):
        for l in range(image_weight):
            (b,g,r)=src[k][l]
            dst2[k][l]=src[k][l]
            if (b,g,r) in color:
                #dst2[k][l]=(255,255,255)
                dst2[k][l]=(173,206,123)
    
    #cv2.imshow('dst',dst2)
    #cv2.imwrite('.\\img1\\'+str(m),dst2)
    cv2.imencode('.png', dst2)[1].tofile(fname)
    #cv2.waitKey(0)

def changewz(fname):   #黑色文字颜色处理
    #src=cv2.imread(fname,1)
    src = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1)
    img_info=src.shape
    image_height=img_info[0]
    image_weight=img_info[1]
    dst=np.zeros((image_height,image_weight,3),np.uint8)
    for i in range(image_height):
        for j in range(image_weight):
            (b,g,r)=src[i][j]
            if b<80 and g<80 and r<80 :   #过滤黑色
                #dst[i][j]=(255-r,255-g,255-b)
                dst[i][j]= (173,206,123)

            #if b>150 and g<150 and g>70 and r>150 and r<180 :   #过滤紫色
            #    #dst[i][j]=(255-r,255-g,255-b)
            #    dst[i][j]= (173,206,123)       
            
            else :
                dst[i][j]=src[i][j]
    #cv2.imshow('src',src)
    #cv2.imshow('dst',dst)
    #cv2.imwrite(fname,dst) 
    pname='.\\png\\yzm'+time.strftime("%H%M%S")+'.png'
    #cv2.imencode('.png', dst)[1].tofile('.\\png\\yzm1.png')
    cv2.imencode('.png', dst)[1].tofile(pname)
    cv2.waitKey(0)
    return pname



def rndCharImg(yzmwz):         #生成验证码颜色说明文字图片                    
    #charimage = Image.new('RGB',(120, 40), (0,0,0))       # 创建新的图像
    charimage = Image.new('RGB',(90, 20), (255,255,255))
    drawChar =ImageDraw.Draw(charimage)                  # 创建可绘画对象
    #font = ImageFont.truetype('d:\\tensorflow\\font\\Mirvoshar.ttf', 22)           # 定义字体参数
    font = ImageFont.truetype('st.otf',9)
    #zm=rndChar()
    zm= yzmwz
    #zm=zm[6:]
    #print(zm)
    drawChar.text((5,0),zm,font=font,fill=(0,0,0))  #生成文字图片
    #drawChar.text((5, 5), zm, font = font,fill=(255,0,0))
    #drawChar.text((5, 5), rndChar(), font = font,fill=(255,0,0))  # 添加字母到图像中
    #charimage = charimage.rotate(rndRotate())            # 旋转图像
    return charimage,zm                                     # 返回生成的字母图像

def yzmtxt(text1):  #获取验证码颜色文字
    while 1:
        if text1=='请输入验证码图片中黄色文字':
            text1=text1[6:]
            #text1='yellow'
            break
            #driver.find_element_by_id("yzm_img").screenshot('D:\\python\\fapiao\\png\\yzmyellow'+str(i)+'.png')
        if text1=='请输入验证码图片中蓝色文字':
            text1=text1[6:]
            break
            #driver.find_element_by_id("yzm_img").screenshot('D:\\python\\fapiao\\png\\yzmblue'+str(i)+'.png')
        if text1=='请输入验证码图片中红色文字':
            text1=text1[6:]
            break
            #driver.find_element_by_id("yzm_img").screenshot('D:\\python\\fapiao\\png\\yzmred'+str(i)+'.png')
        if text1=='请输入验证码文字':
            #driver.find_element_by_id("yzm_img").screenshot('D:\\python\\fapiao\\png\\yzm'+str(i)+'.png')
            text1=text1[1:]
            break
        else :
            time.sleep(1)
            print ('等待验证码5秒')
        #    driver.find_element_by_id("yzm_img").click()
            break
    #print (text1)
    return text1



def gen_captcha_text_and_image(yzmwz,i,fname):  #生成上传用的打码图片
    # 创建主图像
    #width = 120*1                                   # 设置图像的宽为120
    #height = 90                                    # 设置图像的高为90
    width = 180
    height =90
    image = Image.new('RGB', (width, height), (255, 255, 255))      # 创建主图像
    draw = ImageDraw.Draw(image)                   # 创建可绘画对象

    # 添加字母到主图像中

    for t in range(1):                             
        img,captcha_text = rndCharImg(yzmwz)
        r, g, b= img.split()                       # 分离图层
        #image.paste(img, (5* t, 55),r)      # 把文字图像粘贴到r图层中
        image.paste(img, (60*t, 71))
        #fname = './png/yzmimg'+str(i)+'.png'  #打开验证码图片
        img2 = Image.open(fname)
        img2 =img2.resize((180,70),Image.ANTIALIAS)  #放大2倍
        image.paste(img2, (0, 0))              #粘贴验证码图片部分
        image.save('./png/yzm'+str(i)+'.png',"png")  #保存图片
    # 保存图像
    #image.save('D:\\tensorflow\\captcha\\png\\'+code+'-yzm'+str(i)+'.png', 'png')
    captcha_image=image
    captcha_image=np.array(captcha_image)
    return captcha_text, captcha_image

def hctp(i,text1):
    text, image = gen_captcha_text_and_image(text1)
    gray = np.mean(image, -1)
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.text(0.1, 0.9, text, ha='center', va='center', transform=ax.transAxes)
    
    #plt.imshow(image)
    
    #plt.show()
    pname='./png/yzm'+str(i)+'.png'
    plt.imsave(pname,image)
    return pname


def is_contains_chinese(strs): #检查验证码中是否有中文
    for _char in strs:
        if '\u4e00' <= _char <= '\u9fa5':
            return True
    return False

def rcsv2(path):  #读取发票文件
    f = open(path, 'rb')
    data = pd.read_csv(f, nrows=0)  #读取表头
    headlist = data.columns.tolist()  #表头存入列表
    print(headlist)
    f.close()

    f = open(path, 'rb')
    data = pd.read_csv(f)
    X = data[headlist]  # 读取行
    x_list = X.values.tolist()  # list
    
    #print('显示行:',x_list[1][0],x_list[1][1],x_list[1][2],x_list[1][3])
    f.close()
    return x_list

#def rcfg():   #获取发票查询记录数
#    f = open('cfg.csv', 'r')
#    csvreader = csv.reader(f)
#    item = list(csvreader)
#    #item=final_list
#    #item = csvreader
#    v1=int(item[0][0])
#    v2=int(item[1][0])
#    print (v1,v2)
#    return v1,v2

def captcha_img_ocr(input_color=None):  #cnn把图片转换成文字,颜色列表,保存验证码文件
    '''
    :param input_color: 要求输入的颜色
    :return:待输入字符串
    '''
    filename = '.\\png\\'+time.strftime("%Y%m%d-%H%M%S")+'.png'   #时间定义文件名
    
    k=0
    while k<3:
        try :
            src = browser.find_element_by_id('yzm_img').get_property('src')  #base64图片获取
            img = base64.b64decode(src.split(',')[-1])
            with open(filename, 'wb') as f:
                f.write(img)
            strings, colors = predict(filename)  #老模型识别
        
            if input_color:
                res = ""
                for char,_color in zip(strings,colors):
                    if _color == input_color:
                        res += char
            else:
                res = "".join(strings)
            k=4    
        except: #获取验证码图片失败，就送一张临时图       
            print ('验证码无响应',k)
            #browser.find_element_by_css_selector('#imgarea a').click()
            filename='.\\png\\img_t.png'
            res='ebbeee'
            time.sleep(1)
            k=k+1
            #print(k)
    #print (res)
    return res,filename  #返回文件名，和颜色序列

def ischs_text():  #获取某个颜色的字符
    try:
        color = browser.find_element_by_css_selector('#yzminfo font').text[0]
    except:
        color = None
    #print(color)
    text,filename = captcha_img_ocr(color)
    
    if color=='红':
        color1='red'
    if color=='黄':
        color1='yellow'
        
    if color=='蓝':
        color1='blue'    
    if color==None:
        color1='black'

    return text,filename,color1

def eng_text(h1): #判断有中文就上云
    i=0
    text,filename,color1=ischs_text()
    if is_contains_chinese(text) :
        i=i+1 #i大于0有中文
        #print ('重置验证码',i,'次')
        #time.sleep(5)  #延时避免没有响应
        if h1=='y':
            text=''
            pass
        else:
            yzmwz = browser.find_element_by_id("yzminfo").text
            text1 = yzmtxt(yzmwz)
            #print (text1)
            #gen_captcha_text_and_image(text1,i,filename)      #合成上传图片
            if color1!='black':  #去除黑色文字，保留单色文字
                bgcl(filename)
                pname=changewz(filename)
                #pname='./png/yzm'+str(i)+'.png'
                
                #pname='./png/yzm'+time.strftime("%H%M%S")+'.png'

            else :
                pname=filename
            
            #pname='./png/yzm'+str(i)+'.png'
            #print('合成图片')
        
            time.sleep(1)
            
            
            text=tj(pname)       #图鉴识别
            
            
    #print (text)
    else:
        if color1=='yellow':  #黄色转红色
            changey(filename)
        if color1=='blue':     #蓝色转红色
            changeb(filename) 

        fn1,fn2=qg1(filename)   #切割成两张
        yzmjg,color3=predict3(fn1)  #识别3字符
        #print(yzmjg,color)
        yzmjg1,color31=predict3(fn2)   #识别3字符
        yzmjg.extend(yzmjg1)           #连接识别结果
        color3.extend(color31)          #连接识别颜色
        if color1!='black':             #不是黑色的就直接识别红色
            res = ""
            for char,_color in zip(yzmjg,color3):
                if _color == '红':
                    res += char            #返回红色字符
        else:
            res = "".join(yzmjg)        #返回黑色字符
        print('3CHAR',res)
        text=res        

    
    return text,i

def set_text(h1):  #获得验证码文字
   
    text,c1=eng_text(h1)
    if h1=='y' and c1>0:  #如果手工且有中文
        time.sleep(1)
        pass
    else:
    #print(is_contains_chinese(text))  #判定是否有中文
        browser.find_element_by_css_selector('#yzm').clear()
        browser.find_element_by_css_selector('#yzm').send_keys(text)
    return text


if __name__ == "__main__":
    v1,v2,v3,v4,v5,v6,v7,v8=readpz()  #读取参数
    
    chrome_options = Options()
    #chrome_options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--ignore-certificate-errors')  #忽略证书错误
    chrome_options.add_argument('--window-size=1366,768')       #设置窗口大小
    
    browser = webdriver.Chrome(chrome_options=chrome_options)
    #driver = Chrome('C:\\Program Files (x86)\\Google\\Chrome\\Application')
    browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        Object.defineProperty(navigator, 'webdriver', {
        get: () => undefined
        })
    """
    })  #防止web-navigator-debug检测
    browser.get("https://inv-veri.chinatax.gov.cn")
   
    print(browser.title) 

    path=v4
    fplist=rcsv2(path)   #获取csv内容
    #v1,v2=rcfg()
    
    now = datetime.now()
    clickcoun=0
    for i in range(int(v1),int(v2)):  #获取订单数量
        count=0  #限制while次数
        SR1=0    #输入参数，是否需要重新输入
        CFCX=0   #限制当日查询超限
        yzmerr=0  #验证码错误次数
        
        while count<4 :
            if clickcoun%10==9:   #避免验证码频繁 
                #browser.get("https://www.baidu.com")
                #time.sleep(1)
                browser.close()
                
                time.sleep(1)
                print('页面重置北京',clickcoun)
                #browser.find_element_by_css_selector('#yzm').send_keys('aaaaaa')
                #browser.find_element_by_css_selector('#checkfp').click()
                browser = webdriver.Chrome(chrome_options=chrome_options)
                #driver = Chrome('C:\\Program Files (x86)\\Google\\Chrome\\Application')
                browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
                "source": """
                    Object.defineProperty(navigator, 'webdriver', {
                    get: () => undefined
                    })
                """
                })  #防止web-navigator-debug检测


            #browser.get("http://inv-veri.chinatax.gov.cn")
            browser.get("https://inv-veri.chinatax.gov.cn/index.html")
            time.sleep(1)
            #browser.find_element_by_css_selector('#fpdm').send_keys(str(int(fplist[i][0])))
            dm0=str(int(fplist[i][0]))
            if len(dm0)>10 :
                browser.find_element_by_css_selector('#fpdm').send_keys(dm0.zfill(12))
            if len(dm0)==10 :
                browser.find_element_by_css_selector('#fpdm').send_keys(dm0.zfill(10))
            hm1=str(int(fplist[i][1]))
            browser.find_element_by_css_selector('#fphm').send_keys(hm1.zfill(8))
            browser.find_element_by_css_selector('#kprq').send_keys(str(fplist[i][2]))
            if v6=='pp' :  #普票校验码类型
                ck0=str(int(fplist[i][3]))
            else :
                ck0=str(fplist[i][3])
            #print (ck0)
            #print (ck0.zfill(6))
            browser.find_element_by_css_selector('#kjje').send_keys(ck0.zfill(6))
            time.sleep(1)
            text=set_text(v7)
            try :  #检查是否频繁1
                t1=browser.find_element_by_css_selector('#popup_title').text
                print ('弹出标题',t1)
                if t1=='警告':
                    print  ('验证码频繁1')
                    time.sleep(60)
                    
                    if v3=='y':
                        chrome_options.add_argument('--headless') #无界面浏览器
                    if v3=='n':
                        pass    
                    
                    continue #重新输入四要素
            except :
                pass

            #####输入要素完成
            browser.find_element_by_css_selector('#yzminfo').click()
            check = browser.find_element_by_css_selector('#checkfp')
            time.sleep(1)
            print('显示查验',browser.find_element_by_css_selector('#uncheckfp').is_displayed())  #false代表查验按钮有效
            #print('显示count',count)
            try :
                
                check.click()
                clickcoun=clickcoun+1
                print (str(i),'张count',count,'次点击查验')
                time.sleep(1)
            except :
                count=count+1
                print ('第',count,'check无效')
                continue   #查验按钮无效，重新输入四要素
            try:
                popup = browser.find_element_by_css_selector('#popup_ok')  #是否有弹出框
                t2=browser.find_element_by_css_selector('#popup_message').text
                yzmerr=yzmerr+1
                print ('弹出1',t2,yzmerr)
                if t2=='超过该张发票当日查验次数(请于次日再次查验)!':
                    break  #跳出这张发票
                time.sleep(1)
            except:
                popup = None
            
            while popup:  # 输错后弹窗，点击换验证码，反复输入
                if clickcoun%10==9:  #避免验证码频繁
                    browser.close()
                    #browser.delete_all_cookies()
                    browser = webdriver.Chrome(chrome_options=chrome_options)
                    #driver = Chrome('C:\\Program Files (x86)\\Google\\Chrome\\Application')
                    browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
                    "source": """
                        Object.defineProperty(navigator, 'webdriver', {
                        get: () => undefined
                        })
                    """
                    })  #防止web-navigator-debug检测
                    clickcoun=clickcoun+1
                    break


                try :
                    popup.click()
                    browser.find_element_by_css_selector('#imgarea a').click()
                    time.sleep(1)
                    set_text(v7)
                except :
                    break  #跳出popup  
                
                try :  #再次检查频繁
                    t1=browser.find_element_by_css_selector('#popup_title').text
                    #print ('弹出标题',t1)
                    t2=browser.find_element_by_css_selector('#popup_message').text
                    if t2=='验证码错误':
                        yzmerr=yzmerr+1
                    print ('弹出2',t2,yzmerr)
                    
                    
                    if t1=='警告':
                        print  ('验证码频繁2')
                        time.sleep(60)
                        
                        if v3=='y':
                            chrome_options.add_argument('--headless') #无界面浏览器
                        if v3=='n':
                            pass
                        
                        break  #跳出popup的while
                    if t2=='超过该张发票当日查验次数(请于次日再次查验)!':
                        CFCX=1
                        break  #跳出popup的while
                    time.sleep(1)
                except :
                    pass
                
                try :
                    browser.find_element_by_css_selector('#yzminfo').click()
                    print('显示查验',browser.find_element_by_css_selector('#uncheckfp').is_displayed())
                    check.click()
                    clickcoun=clickcoun+1
                    print (str(i),'张count',count,'二次点击查验')
                    time.sleep(1)
                except :
                    
                    SR1=1    
                    count=count+1
                    print ('第',count,'查验按钮无效')
                    #continue #查验按钮无效，就重新输入四要素
    
                try:
                    popup = browser.find_element_by_css_selector('#popup_ok')
                    t2=browser.find_element_by_css_selector('#popup_message').text
                    yzmerr=yzmerr+1
                    print ('弹出3',t2,yzmerr)
                    if t2=='超过该张发票当日查验次数(请于次日再次查验)!':
                        CFCX=1
                        break  #跳出popup的while
                    time.sleep(1)
                except:
                    popup = None
            
            if SR1==1 :
                SR1=+1 #避免死循环
                continue #返回输入这张发票的while        
            else:
                pass
            
            if CFCX==1:
                break #跳出这张发票的while

            time.sleep(1)
            
            browser.save_screenshot(r'./swpng/sw'+str(int(fplist[i][1]))+".png")
            print ('第',i,'张成功')

            
            
            try :
                browser.switch_to.frame('dialog-body')
                cs=browser.find_element_by_css_selector('#cycs').text  #检查查验次数
                t3='查验一致'+cs
                #print(t3)
            except :
                t3='查验失败'
                #print (t3)
                #pass

                try :
                    #browser.switch_to.frame('dialog-body')
                    t3=browser.find_element_by_css_selector('#cyjg').text #返回错误结果
                    #print ('结果',t3)
                except :
                    #t3='查验一致0'
                    #print(t3)
                    count =count+1
                    
                    t3=('第',count,'次失败')  #没有弹出结果
                    print (t3)
                    continue                  #重新输入四要素
            print ('结果',t3)
            #记录日志
            str1=str(int(fplist[i][0]))+","+str(int(fplist[i][1]))+','+str(fplist[i][2])+','+str(fplist[i][3])+',成功,'+str(i)+','+t3
            list1=[]
            list1.append(str1)
            with open(v5, 'a+', newline='') as csvfile:
                writer  = csv.writer(csvfile)
                for row in list1:
                    writer.writerow([row])            
            
            
            break #跳出输入while,进入下一条
        
            
    
    end = datetime.now()
    print ((end-now),'秒') 
    browser.quit()
    #os.system("killc.bat")